﻿namespace Leetcode.N0819;

public class Solution
{
    public string MostCommonWord(string paragraph, string[] banned)
    {
        var hasSetBanned = banned.ToHashSet();
        var wordsCount = new Dictionary<string, int>();
        var maxCount = 0;
        var maxCountWord = "";

        for (int i = 0; i < paragraph.Length; i++)
        {
            if ((paragraph[i] >= 'a' && paragraph[i] <= 'z') || (paragraph[i] >= 'A' && paragraph[i] <= 'Z'))
            {
                var word = this.ReadWord(paragraph, ref i);
                if (hasSetBanned.Contains(word))
                {
                    continue;
                }

                if (!wordsCount.ContainsKey(word))
                {
                    wordsCount.Add(word, 1);
                }
                else
                {
                    wordsCount[word]++;
                }

                if (wordsCount[word] > maxCount)
                {
                    maxCount = wordsCount[word];
                    maxCountWord = word;
                }
            }
        }
        return maxCountWord;
    }

    internal string ReadWord(string paragraph, ref int index)
    {

        var list = new List<char>();
        list.Add((paragraph[index] >= 'a' && paragraph[index] <= 'z') ? paragraph[index] : (char)(paragraph[index] - 'A' + 'a'));

        for (int i = index + 1; i < paragraph.Length; i++)
        {
            if (paragraph[i] >= 'a' && paragraph[i] <= 'z')
            {
                list.Add(paragraph[i]);
                index++;
                continue;
            }

            if (paragraph[i] >= 'A' && paragraph[i] <= 'Z')
            {
                list.Add((char)(paragraph[i] - 'A' + 'a'));
                index++;
                continue;
            }
            break;
        }
        return new string(list.ToArray());
    }
}
